<?php
namespace app\factory\wxPay;

use app\libs\Util;
use think\facade\Config;

class CompanyPay
{
    //企业付款给用户

	private $appid="";//申请商户号的appid或商户号绑定的appid
	private $mch_id="";//商户号
	private $nonce_str;//随机字符串最高32位
	private $sign;//签名
	private $partner_trade_no;//商户订单号
	private $openid;//用户openid
	private $check_name="NO_CHECK";//校验用户姓名选项
	private $amount;//金额
	private $desc="收益余额提现";//企业付款备注
	private $spbill_create_ip;//Ip地址
	private $key="";//秘钥
	
	//构造
    public function __construct()
    {
        $this->appid = Config::get('system.wx_pay.app_id');//小程序id
        $this->mch_id = Config::get('system.wx_pay.mch_id');//获取小程序mch_id
        $this->key = Config::get('system.wx_pay.key');//获取小程序key
    }

	/**
	* 企业付款
	* @param $data[pay_sn]支付编号
	* @param $data[pay_amount]支付金额
	*/
	public function confirm_pay($data=[]){
		$this->nonce_str=md5(time());//生成随机字符串
		$this->spbill_create_ip=request()->ip();//终端ip

		$this->partner_trade_no=$data['pay_sn'];//支付编号
		$this->amount=($data['pay_amount']*100);//支付价格-单位分
		$this->openid=$data['openid'];//微信 openid
		
		//ASCII排序 a b c d e f g h i j k l m n o p q r s t u v w x y z
		$strA="";
		$strA.="amount=".$this->amount;
		$strA.="&check_name=".$this->check_name;
		$strA.="&desc=".$this->desc;
		$strA.="&mch_appid=".$this->appid;
		$strA.="&mchid=".$this->mch_id;
		$strA.="&nonce_str=".$this->nonce_str;
		$strA.="&openid=".$this->openid;
		$strA.="&partner_trade_no=".$this->partner_trade_no;
		$strA.="&spbill_create_ip=".$this->spbill_create_ip;
		$strA.="&key=".$this->key;
		$this->sign=strtoupper(md5($strA));//转大写
		
		$xml="<xml>
			<amount>".$this->amount."</amount>
			<check_name>".$this->check_name."</check_name>
			<desc>".$this->desc."</desc>
			<mch_appid>".$this->appid."</mch_appid>
			<mchid>".$this->mch_id."</mchid>
			<nonce_str>".$this->nonce_str."</nonce_str>
			<openid>".$this->openid."</openid>
			<partner_trade_no>".$this->partner_trade_no."</partner_trade_no>
			<spbill_create_ip>".$this->spbill_create_ip."</spbill_create_ip>
			<sign>".$this->sign."</sign>
			</xml>";

		$url="https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";//访问企业付款url
		$wxpay=Util::post_request_ssl($url,$xml);//访问数据
		$wxpay = json_decode(json_encode( simplexml_load_string($wxpay, 'SimpleXMLElement', LIBXML_NOCDATA) ),true);
		return $wxpay;

	}

}